package edu.llg.oojcodesandbox.utils;

import cn.hutool.core.date.StopWatch;
import edu.llg.oojcodesandbox.model.ExecuteCodeResult;
import edu.llg.oojcodesandbox.model.ExecuteMessage;
import edu.llg.oojcodesandbox.model.JudgeInfo;

import java.io.BufferedReader;
import java.io.InputStreamReader;
import java.util.ArrayList;
import java.util.List;

/**
 * @author 隆利果
 * @version 1.0
 * @date 2024/2/7 20:47
 */
public class ProcessExecuteUtil {

    public static ExecuteMessage runProcess(Process process,String opName){
        ExecuteMessage executeMessage = new ExecuteMessage();

        try {
            StopWatch stopWatch = new StopWatch();
            stopWatch.start();
            /**
             * 等待程序执行拿到结果
             */
            int exitValue = process.waitFor();
            executeMessage.setExitValue(exitValue);

            JudgeInfo judgeInfo = new JudgeInfo();

            //正常退出
            if(exitValue == 0){
                BufferedReader bufferedReader = new BufferedReader(new InputStreamReader(process.getInputStream()));
                List<String> outputList = new ArrayList<>();
                String compileOutputLine = new String();
                while ((compileOutputLine = bufferedReader.readLine()) != null){
                    outputList.add(compileOutputLine);
                }
                StringBuilder sb = new StringBuilder();
                for (int i = 0; i < outputList.size(); i++) {
                    sb.append(outputList.get(i));
                    if(i != outputList.size()-1){
                        sb.append("\n");
                    }
                }
                judgeInfo.setMessage(sb.toString());
                System.out.println(opName+" 成功 "+sb.toString());
            }else{
                BufferedReader bufferedReader = new BufferedReader(new InputStreamReader(process.getErrorStream()));
                List<String> outputList = new ArrayList<>();
                String compileOutputLine = new String();
                while ((compileOutputLine = bufferedReader.readLine()) != null){
                    outputList.add(compileOutputLine);
                }
                StringBuilder sb = new StringBuilder();
                for (int i = 0; i < outputList.size(); i++) {
                    sb.append(outputList.get(i));
                    if(i != outputList.size()-1){
                        sb.append("\n");
                    }
                }
                judgeInfo.setMessage(sb.toString());
            }
            stopWatch.stop();
            judgeInfo.setTime(stopWatch.getLastTaskTimeMillis());
            // todo 获取消耗的内存
            executeMessage.setJudgeInfo(judgeInfo);
            System.out.println("=============结束=============");
        } catch (Exception e) {
            throw new RuntimeException(e);
        }
        return executeMessage;
    }
}
